<template>
  <div class="container">
    <div class="flex flex-wrap f-ptp10">
      <el-input class='f-mrt20 f-mbt10 f-w120' clearable v-model="id" placeholder="项目ID"></el-input>
      <el-input class='f-mrt20 f-mbt10 f-w120' clearable v-model="title" placeholder="项目名称"></el-input>
      <el-select class='f-mrt20 f-mbt10 f-w120' v-model="state" clearable placeholder="请选择">
        <el-option
          clearable
          v-for="item in states"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-date-picker
        class='f-mrt20 date'
        v-model="date"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期">
      </el-date-picker>
      <el-button class='f-h40 f-mrt20' @click="getList" type="primary">查询</el-button>
      <router-link class='f-h40 add-btn' to="/home/publicWelfare/addProject" >新增项目</router-link>
    </div>
    <div>
      <el-table
        :data="projectList"
        border
        style="width: 100%">
        <el-table-column prop="id" label="项目ID" width="180"></el-table-column>
        <el-table-column prop="title" label="项目名称" width="180"></el-table-column>
        <el-table-column prop="targetMoney" label="募集金额" width="180"></el-table-column>
        <el-table-column prop="money" label="已募集金额" width="180"></el-table-column>
        <el-table-column prop="createTime" label="发生时间" width="180">
          <template slot-scope="scope">
            <span>{{tranDate(scope.row.createTime)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="当前状态" width="180">
          <template slot-scope="scope">
            <span v-if="scope.row.state == 'finished'">已结束</span>
            <span v-if="scope.row.state == 'progressing'">募集中</span>
          </template>
        </el-table-column>
        <el-table-column prop="manage" label="管理">
          <template slot-scope="scope">
            <router-link class='s-c-green f-csp f-mrt10' :to='"/home/publicWelfare/editProject/"+ scope.row.id' >编 辑</router-link>
            <span @click='addProgressBtnClickEvent(scope.row)' class='s-c-green f-csp f-mrt10'>添加进度</span>
            <router-link class='s-c-green f-csp f-mrt10' :to='"/home/publicWelfare/detail/"+ scope.row.id' >项目详情</router-link>
            <span @click='deletedBtnClickEvent(scope.row)' class='s-c-red f-csp f-mrt10'>删 除</span>
          </template>
        </el-table-column>
      </el-table>
      <div class='f-ptp20 f-pbt20'>
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          background
          :total="totalCount">
        </el-pagination>
      </div>
    </div>

    <!-- 添加项目进度 -->
    <el-dialog
      title="添加进度"
      :visible.sync="showAddProgress"
      width="800px"
      :before-close="handleClose">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="项目编号">
          <span>{{form.id}}</span>
        </el-form-item>
        <el-form-item label="发生时间">
          <el-col :span="11">
            <el-date-picker type="date" placeholder="选择日期" v-model="form.createTime" style="width: 100%;"></el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="进度标题">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="进度描述">
          <quill-editor
            v-model="form.description"
            placeholder="fsfsf"
            ref="myQuillEditor"
            :options="editorOption"
            @change="onEditorChange"
          ></quill-editor>
          <input v-show='false' type="file" @change="upImg" id='upImg' ref="upImg" accept="image/png, image/jpeg, image/gif, image/jpg" />
          <!-- <el-input type="textarea" v-model="form.description"></el-input> -->
        </el-form-item>
        <el-form-item label="添加图片">
          <div class="u-upload">
            <input
              type="file"
              @change="upCoverImg"
              ref="addFile"
              name="file"
              id="file"
              accept="image/png, image/jpeg, image/gif, image/jpg"
              class="u-upload-file"
            >
            <label for="file" class="btn btn-success">
              <img v-if="form.picUrl" :src="form.picUrl" alt="">
              <i class='el-icon-plus' v-else></i>
            </label>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">添加</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import config from '../../config'
export default {
  name: 'PublicWelfareManage',
  data() {
    return {
      editorOption: {
        theme: "snow",
        placeholder: "请在此输入咨询记录...",
        modules: {
          toolbar: {
            container: config.toolbarOptions,
            handlers: {
              'image': function(value) {
                if(value) {
                  document.querySelector('#upImg').click()
                } else {
                  this.quill.format('image', false);
                }
                
              }
            }
          }
        }
      }, // 富文本配置
      id: '',
      title: '', // 项目名称
      state: '', // 状态，progressing("进行中"), finished("已完成");
      date: '',
      states: [
        {
          label: '募集中',
          value: 'progressing'
        },
        {
          label: '已结束',
          value: 'finished'
        }
      ],
      form: { // 添加进度表单
        id: '',
        name: '',
        description: '',
        picUrl: '',
        createTime: '',
      },
      showAddProgress: false,
      currentPage: 1,
      pageSize: 10,
      totalCount: 0,
      projectList: []
    }
  },
  created() {
    this.getList();
  },
  methods: {
    // 删除按钮点击事件
    deletedBtnClickEvent(project) {
      this.$confirm('确定删除该项目？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('UPDATE_PROJECT', {
          id: project.id,
          state: 'deleted'
        }).then(res => {
          if(res.data.retCode == 0) {
            this.$message.success('已成功删除！');
            this.getList();
          } else {
            res.data.errorMsg && this.$message.warning(res.data.errorMsg);
          }
        })
      })
    },
    onEditorChange({ quill, html, text }) {
      console.log("editor change!-quill", quill, html, text);
      console.log("editor change!-html", html);
      console.log("editor change!-text", text);
      this.form.description = html;
    },
    // 日期转换
    tranDate(date) {
      return this._utils.format(date, 'yyyy-mm-dd');
    },
    // 获取项目列表
    getList() {
      let startDay = '';
      let endDay = '';
      if(this._utils.getType(this.date) == 'Array') {
        startDay = this._utils.format(this.date[0], 'yyyy-mm-dd');
        endDay = this._utils.format(this.date[1], 'yyyy-mm-dd');
      }
      this.$store.dispatch('GET_PROJECT_LIST', {
        pageNum: this.currentPage - 1,
        pageSize: this.pageSize,
        id: this.id,
        title: this.title,
        state: this.state,
        startDay,
        endDay,
      }).then(res => {
        if(res.data.retCode == 0) {
          this.projectList = res.data.data;
          this.totalCount = res.data.totalCount;
        } else {
          res.data.errorMsg && this.$message.warning(res.data.errorMsg);
        }
      })
    },

    // 添加进度按钮点击事件
    addProgressBtnClickEvent(project) {
      this.form.id = project.id;
      this.showAddProgress = true
    },

    // 添加进度弹窗-添加按钮点击事件
    onSubmit() {
      if(this._utils.isEmpty(this.form.createTime)) {
        this.$message.warning('请选择发生日期！');
        return;
      }
      if(this._utils.isEmpty(this.form.name)) {
        this.$message.warning('请填写进度标题！');
        return;
      }
      if(this._utils.isEmpty(this.form.description)) {
        this.$message.warning('请填写进度描述！');
        return;
      }
      this.addProgress();
    },

    // 添加进度
    addProgress() {
      this.$store.dispatch('UPDATE_PROJECT_PROGRESS', {
        projectId: this.form.id,
        name: this.form.name,
        description: this.form.description,
        picUrl: this.form.picUrl,
        createTime: this._utils.format(this.form.createTime),
      }).then(res => {
        if(res.data.retCode == 0) {
          this.$message.success('添加成功！');
          this.showAddProgress = false;
        } else {
          res.data.errorMsg && this.$message.warning(res.data.errorMsg);
        }
      });
    },

    // 初始化 添加进度表单
    initForm() {
      this.form.id = '';
      this.form.name = '';
      this.form.description = '';
      this.form.picUrl = '';
      this.form.createTime = '';
    },
    // 上传封面图片
    upCoverImg(e) {
      this.upfile(e, 'cover')
    },
    // 富文本上传图片
    upImg(e) {
      this.upfile(e, 'editor')
    },
    // 上传图片
    upfile(e, type) {
      const files = e.target.files;
      const form = new FormData();
      form.append("file", files[0]);
      form.append("dir", "project");
      form.append("type", "1");
   
      this.$store.dispatch("UPLOAD_FILE", form).then(res => {
        if(res.data.retCode == 0) {
          this.$message.success('上传成功！');
          if(type == 'cover') {
            this.form.picUrl = res.data.data;
          }
          if(type == 'editor') {
            // 获取富文本组件实例
            let quill = this.$refs.myQuillEditor.quill;
            // 获取光标所在位置
            let length = quill.getSelection().index;
            // 插入图片，res为服务器返回的图片链接地址
            quill.insertEmbed(length, 'image', res.data.data)
            // 调整光标到最后
            quill.setSelection(length + 1)
          }
        } else {
          res.data.errorMsg && this.$message.warning(res.data.errorMsg);
        }
      });
    },

    // 添加进度弹窗关闭前回调函数
    handleClose() {
      this.initForm();
      this.showAddProgress = false;
    },

    handleCurrentChange(page) {
      this.currentPage = page;
      this.getList();
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.add-btn{
  display: inline-block;
  line-height: 1;
  white-space: nowrap;
  cursor: pointer;
  background: #fff;
  border: 1px solid #409EFF;
  /* color: #606266; */
  -webkit-appearance: none;
  text-align: center;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  outline: 0;
  margin: 0;
  -webkit-transition: .1s;
  transition: .1s;
  font-weight: 500;
  padding: 12px 20px;
  font-size: 14px;
  border-radius: 4px;
  color: #fff;
  background-color: #409EFF;
}
.add-btn:hover{
  background: #66b1ff;
  border-color: #66b1ff;
  color: #fff;
}
.top{
  /* display: flex; */
  overflow: hidden;
  padding: 10px 0;
}
.top-item{
  float: left;
  margin-right: 20px;
}
.w-120{
  width: 120px;
}
.w-200{
  width: 200px;
}
</style>
